package com.imooc.springmvc3;

import com.imooc.springmvc3.interceptor.DemoInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

/**
 * springmvc配置类
 * 作用:
 *      取代xml配置文件
 *
 * spring MVC的定制配置需要我们的配置继承一个WebMvcConfigurerAdapter类,并在此类使用@EnableWebMvc注解,
 * 来开启对Spring mvc 的配置支持,这样我们就可以重写这个类的方法,完成我们的配置
 * Created by joe on 16-8-11.
 */
@Configuration
@EnableWebMvc
@ComponentScan("com.imooc.springmvc3")
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Bean//返回bean组件,view视图
    public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/classes/views/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setViewClass(JstlView.class);
        return viewResolver;
    }

    /**
     * 重写addResourceHandlers方法
     * addResourceLocations:指的是文件放置的目录
     * addResourceHandler:值得是对外暴露的访问路径
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/asset/");
    }

    @Bean//配置拦截器bean,加入ioc容器管理
    public DemoInterceptor demoInterceptor(){
        return new DemoInterceptor();
    }

    /**
     * 重写addInterceptors方法,注册拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(demoInterceptor());
    }
}
